using System;
using System.ComponentModel;
using System.IO;
using RollManager.Library.Utils;

namespace RollManager.Library.ActionSteps
{
    [Serializable]
    public class RenameFilesStep : ActionStep
    {
        private string m_oldFileName = StepConstants.NAME;
        private string m_newFileName = StepConstants.NAME;

        [DisplayName( "New File Name" )]
        [Description( "The new name of the file." )]
        public string NewFileName
        {
            get
            {
                return m_newFileName;
            }
            set
            {
                if( string.IsNullOrEmpty( value ) )
                {
                    throw new ArgumentException( "New File Name cannot be empty." );
                }
                else
                {
                    m_newFileName = value.Trim();
                }
            }
        }

        [DisplayName( "Old File Name" )]
        [Description( "The old name of the file." )]
        public string OldFileName
        {
            get
            {
                return m_oldFileName;
            }
            set
            {
                if( string.IsNullOrEmpty( value ) )
                {
                    throw new ArgumentException( "Old File Name cannot be empty." );
                }
                else
                {
                    m_oldFileName = value.Trim();
                }
            }
        }

        public override string Name
        {
            get { return "Rename Files"; }
        }

        protected override void Run()
        {
            MethodRepeater.RepeatMethod( delegate
            {
                FileInfo file = new FileInfo( m_oldFileName );
                file.MoveTo( m_newFileName );
            }, Progress, 5 );
        }

        protected override void Simulate()
        {
            // Check for old file name
            FileInfo file = new FileInfo( m_oldFileName );
            if( !file.Exists )
            {
                throw new Exception( string.Format( "Old file name {0} does not exist.", m_oldFileName ) );
            }

            // Check for new file name
            file = new FileInfo( m_newFileName );
            if( file.Exists )
            {
                throw new Exception( string.Format( "New file name {0} already exists.", m_newFileName ) );
            }

            Progress.AddFormat( "Simulated rename of {0} to {1}", m_oldFileName, m_newFileName );
        }
    }
}
